﻿using System.Collections.Generic;
using System.Linq;
using Snake.Gameplay.EffectComponents;

namespace Snake.Gameplay
{
    public class GameplayEffectsContainer
    {
        private readonly List<GameplayEffectSpec> _addEffects = new List<GameplayEffectSpec>();
        private readonly List<GameplayEffectSpec> _removeEffects = new List<GameplayEffectSpec>();

        /// <summary>
        /// 只有Infinite,HasDuration类型的效果
        /// </summary>
        private readonly List<GameplayEffectSpec> _activeEffects = new List<GameplayEffectSpec>();

        public GameplayAbilityComponent Owner { get; }

        public GameplayEffectsContainer(GameplayAbilityComponent owner)
        {
            Owner = owner;
        }

        public void AddEffect(GameplayEffectSpec effect)
        {
            effect.Container = this;
            if (effect.Effect.durationPolicy == DurationPolicy.Instant)
            {
                effect.ApplyInstantAndPeriodic();
                return;
            }

            _addEffects.Add(effect);
        }

        public void RemoveEffectWithTag(string tag)
        {
            _removeEffects.AddRange(_activeEffects.Where(spec =>
                spec.Effect
                    .TryGetComponent(out AssetTags com) &&
                com.CombinedTags.Contains(tag)));
        }

        public void OnUpdate(float dt)
        {
            foreach (var spec in _addEffects)
            {
                spec.OnAdd();
                _activeEffects.Add(spec);
            }

            _addEffects.Clear();

            foreach (var spec in _activeEffects)
            {
                spec.OnUpdate(dt);
                if (spec.IsInvalid)
                {
                    _removeEffects.Add(spec);
                }
            }

            foreach (var spec in _removeEffects)
            {
                spec.OnRemove();
                _activeEffects.Remove(spec);
            }

            _removeEffects.Clear();
        }
    }
}